import Taro, { Component } from '@tarojs/taro'
import {View, Text, ScrollView, Image} from '@tarojs/components'
import './ClassifyPage.scss'
import {getLeftClassIfy} from '../../mode/classifyCtr';

import { AtGrid } from "taro-ui"


class ClassifyPage extends Component{

  config = {
    navigationBarTitleText: '推荐分类'
  }

  componentWillMount() {

  }

  componentDidMount() {
    /* 等待DOM挂载完成 */
    Taro.nextTick(() => {
      /* 在非H5平台，nextTick回调后有概率获取到错误的元素高度，则添加200ms的延迟来减少BUG的产生 */
      setTimeout(() => {
        /* 等待滚动区域初始化完成 */
        this.initScrollView().then(() => {
          /* 获取列表数据，你的代码从此处开始 */
          this.getListData();
        })
      }, 200);
    })

  }

  componentWillUnmount() { }

  componentDidShow() { }

  componentDidHide() { }

  state = {
    scrollHeight: 400,
    scrollTopSize: 0,
    fillHeight: 0,	// 填充高度，用于最后一项低于滚动区域时使用
    leftArray: [],
    mainArray: [],
    topArr: [],
    leftIndex: 0,
    scrollInto: '',
    leftIntoView: `left-0`
  }

  /* 初始化滚动区域 */
  initScrollView = () => {
    var that = this
    return new Promise((resolve, reject) => {
      let view = Taro.createSelectorQuery().select('#scroll-panel');
      view.boundingClientRect(res => {
        that.setState({
          scrollTopSize: res.top,
          scrollHeight: res.height
        }, () => {
          Taro.nextTick(() => {
            resolve();
          })
        })
      }).exec();
    });
  }

  /* 获取列表数据 */
  getListData = () => {
    getLeftClassIfy().then(res=>{
      var left = []
      var main =[]
      res.map((item,index)=>{
        //名字
        left.push(item.main_name)
        //二级
        var list = []
        // console.log(item.data)
        item.data.map((item2,index)=>{
          item2.info.map((item3,index)=>{
            var te = {}
            te.image = item3.imgurl
            te.value = item3.son_name
            list.push(te)
          })
        })
        main.push({
          title: item.main_name,
          listData:list
        })
      })
        // console.log(main[0].listData)
        this.setState({
          leftArray: left,
          mainArray: main
        }, () => {
          // DOM 挂载后 再调用 getElementTop 获取高度的方法。
          Taro.nextTick(() => {
            this.getElementTop();
          });
        })

    })
  }

  /* 左侧导航点击 */
  leftTap = (index) => {
    let leftIndex = (index < 0 ? 0 : index);
    this.setState({
      scrollInto: `item-${index}`,
      leftIndex
    })
  }

  /* 主区域滚动监听 */
  mainScroll = (e) => {
    const { topArr } = this.state
    let top = e.detail.scrollTop;
    let index = 0;
    /* 查找当前滚动距离 */
    for (let i = (topArr.length - 1); i >= 0; i--) {
      /* 在部分安卓设备上，因手机逻辑分辨率与rpx单位计算不是整数，滚动距离与有误差，增加2px来完善该问题 */
      if ((top + 2) >= topArr[i]) {
        index = i;
        break;
      }
    }
    let leftIndex = (index < 0 ? 0 : index);

    this.setState({
      leftIndex,
      leftIntoView: `left-${leftIndex > 3 ? (leftIndex - 3) : 0}`
    })
  }

  /* 获取元素顶部信息 */
  getElementTop = () => {
    const { scrollTopSize, scrollHeight } = this.state
    new Promise((resolve, reject) => {
      let view = Taro.createSelectorQuery().selectAll('.main-item');
      view.boundingClientRect(data => {
        resolve(data);
      }).exec();
    }).then((res) => {
      let topArr = res.map((item) => {
        return item.top - scrollTopSize;	/* 减去滚动容器距离顶部的距离 */
      });
      this.setState({
        topArr
      })

      /* 获取最后一项的高度，设置填充高度。判断和填充时做了 +-20 的操作，是为了滚动时更好的定位 */
      let last = res[res.length - 1].height;
      if (last - 20 < scrollHeight) {
        this.setState({
          fillHeight: scrollHeight - last + 20
        })
      }
    });
  }

  render() {
    const {
      scrollHeight,
      leftArray,
      leftIndex,
      mainArray,
      fillHeight,
      leftIntoView,
      scrollInto
    } = this.state
    return (
      <View className='container'>

        {/* 滚动区域 */}
        <View className='scroll-panel' id='scroll-panel'>
          <View className='list-box'>
            <View className='left'>
              <ScrollView
                scrollY={true}
                style={`height:${scrollHeight}px;`}
                scrollIntoView={leftIntoView}
              >
                {
                  leftArray.map((item, index) => {
                    return (
                      <View
                        className={`item ${index == leftIndex ? 'active' : ''}`}
                        key={index}
                        id={`left-${index}`}
                        onTap={this.leftTap.bind(this, index)}
                      >
                        {item}
                      </View>
                    )
                  })
                }
              </ScrollView>
            </View>

            <View class="main">
              <ScrollView
                scrollY={true}
                style={`height:${scrollHeight}px;`}
                onScroll={this.mainScroll.bind(this)}
                scrollWithAnimation={true}
                scrollIntoView={scrollInto}
              >
                {
                  mainArray.map((item, index) => {
                    // console.log(item.listData)
                    return (
                      <View
                        className='item main-item'
                        key={index}
                        id={`item-${index}`}
                      >
                        <View class="title">
                          <View>{item.title}</View>
                        </View >
                        <AtGrid data={item.listData} onClick={(t)=>{
                          // console.log(t)
                          // url: `/pages/detailPage/detailPage?item=${encodeURIComponent(JSON.stringify(item))}`
                          Taro.navigateTo({
                            url: `/pages/hotSearchPage/hotSearchPage?searchText=`+t.value
                          })
                        }}/>


                        <View className={'lineBom'}></View>
                      </View>

                    )
                  })
                }
                <View className="fill-last" style={`height:${fillHeight};`}></View>

              </ScrollView>
            </View>


          </View>
        </View>

      </View >
    )
  }
}

export  default ClassifyPage
